﻿using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MotionControl.Modules.LightSource.Models;
using MotionControl.Core.Mvvm;
using Prism.Regions;
using Prism.Events;
using MotionControl.Core;
using System.Diagnostics;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Windows.Markup;
using System.Windows.Markup.Localizer;

namespace MotionControl.Modules.LightSource.ViewModels
{
    public class LightSourceViewModel : RegionViewModelBase
    {

        private string _message;

        private IEventAggregator _eventAgg;

        public DelegateCommand Unloaded { get; set; }

        public LightSourceViewModel(IRegionManager regionManager, IEventAggregator aggregator) : base(regionManager)
        {
            _eventAgg = aggregator;
            _eventAgg.GetEvent<LightMsgEvent>().Subscribe(OnLightMsg);
            _eventAgg.GetEvent<MainWindowEvent>().Subscribe(OnMainWindowEvent);
            //Unloaded = new DelegateCommand(OnUnloaded);
        }

        public string Message
        {
            get { return _message; }
            set { SetProperty(ref _message, value); }
        }

        public LightList lightList { get; set; } = LightList.GetInstance;

        private void OnLightMsg(string msg)
        {
            var chan = JsonConvert.DeserializeObject<Channel>(msg);
            foreach (var light in lightList)
            {
                foreach (var channel in light.Channels)
                {
                    try
                    {
                        if (channel.Name == chan.Name)
                        {
                            channel.Intensity = chan.Intensity;
                            break;
                        }                          
                    }
                    catch
                    {
                    }
                }                  
            }
        }
 
        void OnMainWindowEvent(string ev)
        {
            if (ev == "Closed")
                lightList.SaveToJsonFile();
        }
    }
}